package netbayServlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import netbay.TransactionLog;
import netbay.TransactionManager;
import netbay.TransactionTraffic;
import netbay.UserManager;
import netbay.Worker;
import netbay.WorkerManager;
import util.String.StringUtil;

/**
 * Servlet implementation class ReDo
 */
public class ReDo extends HttpServlet {
	public static String recvTcdStatus = "";
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ReDo() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 request.setCharacterEncoding("UTF-8");  // ensures that user input is interpreted as // 8-bit Unicode (e.g., for Czech characters)
	        String userPath = request.getServletPath();
	        response.setContentType("application/json;charset=utf-8");
	        PrintWriter out = response.getWriter();
	        String strJson = "{}";
	        String resultFin = "";
	        HttpSession session = request.getSession();
	        UserManager um = new UserManager();
	        
	        if (userPath.equals("/ReDo/ReTCD")) {
	        	String fileName= (!StringUtil.isNullOrEmpty(request.getParameter("fileName"))) ? request.getParameter("fileName").trim() : "";
	        	String converId= (!StringUtil.isNullOrEmpty(request.getParameter("converId"))) ? request.getParameter("converId").trim() : "";
	        	String type= (!StringUtil.isNullOrEmpty(request.getParameter("type"))) ? request.getParameter("type").trim() : "";

	        	if(type.equals("reJPMCTCD")){
	        		TransactionManager tm = new TransactionManager();
		        	String[] result ;
		        	TransactionLog log = new TransactionLog();
		        	
		        	String ctrlName = fileName.substring(0, fileName.length()-4);
		        	ctrlName += ".ctrl";
		        	File ctrlFile = new File(WorkerManager.TCDRecvDir + "/" + ctrlName);
		        	File xmlFile = new File(WorkerManager.TCDRecvDir + "/" + fileName);
		        	if(ctrlFile.exists()){
			        	TransactionTraffic traffLog  = TransactionTraffic.convertTcdCtrlFile(ctrlFile);
			        	
			        	String sendFileName = traffLog.getTcdAttach();
			        	sendFileName = Worker.convertTCDToJPMC(sendFileName);
			        	traffLog.setConvertFile(sendFileName);
			        	Integer id = tm.getTransactionId(converId);
			        	log.setConverId(converId);
			        	log.setId(id);
			        	traffLog.setTransactionId(id);
			        	traffLog.setType("TCD");
			        	log.setActionType(WorkerManager.ActionTCDToBank);
			        	if (WorkerManager.checkId(converId, WorkerManager.reJPMCTCDCmd)) {
							Worker worker = new Worker(traffLog.getTcdCtrl(),traffLog.getTcdAttach(),WorkerManager.reJPMCTCDCmd);
							 resultFin = worker.sendJPMC(log,traffLog,WorkerManager.reJPMCTCDCmd);
							 if(resultFin.equals("success")){
					        		strJson = "{\"success\": \"\"}";
					        		try {
										um.saveLog((String)session.getAttribute("userId"),UserManager.actionReJPMCTCD,sendFileName);
									} catch (Exception e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
					        	}else strJson = "{\"error\": \"Cannot send file.\"}";
			        	}else strJson = "{\"error\": \"Cannot process.\"}";
		        	}else strJson = "{\"error\": \"Don't have ctrl file.\"}";
		        	
		   		 	out.println(strJson);
	        	}else if(type.equals("reTCDTCD")){
	        		TransactionManager tm = new TransactionManager();
	        		Integer id = tm.getTransactionId(converId);
	        		TransactionTraffic traff = tm.findTraffJpmcAttachByTransactionIdForResend(id);
	        		traff.setConvertFile(fileName);
	    			traff.setTransactionId(id);
	    			traff.setTcdAttach(null);
	    			traff.setTcdCtrl(null);
	    			traff.setTcdMsgId(null);
	    			
	    			TransactionLog log = new TransactionLog();
	    			log.setConverId(converId);
		        	log.setId(id);
		        	log.setActionType(WorkerManager.ActionBankToTCD);
		        	traff.insertJpmcDetail(fileName,log);
		        	traff.setType("TCD");
		        	if (WorkerManager.checkId(converId, WorkerManager.reTCDTCDCmd)) {
						Worker worker = new Worker(fileName,"redownload","",WorkerManager.reTCDTCDCmd);
						resultFin = worker.sendTCD(log,traff,WorkerManager.reTCDTCDCmd);
						if(resultFin.equals("success")){
			        		strJson = "{\"success\": \"\"}";
			        		try {
								um.saveLog((String)session.getAttribute("userId"),UserManager.actionReTCDTCD,fileName);
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
			        	}else strJson = "{\"error\": \"Cannot send file.\"}";
		        	}else strJson = "{\"error\": \"Cannot process.\"}";
		        	
		        	out.println(strJson);
	        	}else if(type.equals("reRDRD")){
	        		TransactionManager tm = new TransactionManager();
	        		Integer id = tm.getTransactionId(converId);
	        		TransactionTraffic traff = tm.findTraffJpmcAttachByTransactionIdForResend(id);
	        		traff.setConvertFile(fileName);
	    			traff.setTransactionId(id);
	    			traff.setTcdAttach(null);
	    			traff.setTcdCtrl(null);
	    			traff.setTcdMsgId(null);
	    			
	    			TransactionLog log = new TransactionLog();
	    			log.setConverId(converId);
		        	log.setId(id);
		        	log.setActionType(WorkerManager.ActionBankToRD);
		        	traff.insertJpmcDetail(fileName,log);
		        	traff.setType("RD");
		        	if (WorkerManager.checkId(converId, WorkerManager.reTCDTCDCmd)) {
						Worker worker = new Worker(fileName,"redownload","",WorkerManager.reTCDTCDCmd);
						resultFin = worker.sendTCD(log,traff,WorkerManager.reTCDTCDCmd);
						if(resultFin.equals("success")){
			        		strJson = "{\"success\": \"\"}";
			        		try {
								um.saveLog((String)session.getAttribute("userId"),UserManager.actionReRDRD,fileName);
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
			        	}else strJson = "{\"error\": \"Cannot send file.\"}";
		        	}else strJson = "{\"error\": \"Cannot process.\"}";
		        	
		        	out.println(strJson);
	        	}else if(type.equals("reJPMCRD")){
	        		TransactionManager tm = new TransactionManager();
		        	String[] result ;
		        	TransactionLog log = new TransactionLog();
		        	
		        	String ctrlName = fileName.substring(0, fileName.length()-4);
		        	ctrlName += ".ctrl";
		        	File ctrlFile = new File(WorkerManager.TCDRecvDir + "/" + ctrlName);
		        	File xmlFile = new File(WorkerManager.TCDRecvDir + "/" + fileName);
		        	if(ctrlFile.exists()){
			        	TransactionTraffic traffLog  = TransactionTraffic.convertTcdCtrlFile(ctrlFile);
			        	
			        	String sendFileName = traffLog.getTcdAttach();
			        	traffLog.setConvertFile(sendFileName);
			        	Integer id = tm.getTransactionId(converId);
			        	log.setConverId(converId);
			        	log.setId(id);
			        	traffLog.setTransactionId(id);
			        	traffLog.setType("RD");
			        	log.setActionType(WorkerManager.ActionRDToBank);
			        	if (WorkerManager.checkId(converId, WorkerManager.reJPMCTCDCmd)) {
							Worker worker = new Worker(traffLog.getTcdCtrl(),traffLog.getTcdAttach(),WorkerManager.reJPMCTCDCmd);
							 resultFin = worker.sendJPMC(log,traffLog,WorkerManager.reJPMCTCDCmd);
							 if(resultFin.equals("success")){
					        		strJson = "{\"success\": \"\"}";
					        		try {
										um.saveLog((String)session.getAttribute("userId"),UserManager.actionReJPMCRD,sendFileName);
									} catch (Exception e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
					        	}else strJson = "{\"error\": \"Cannot send file.\"}";
			        	}else strJson = "{\"error\": \"Cannot process.\"}";
		        	}else strJson = "{\"error\": \"Don't have ctrl file.\"}";
		        	
		   		 	out.println(strJson);
	        	}
	        }
	}

}
